package com.wlts.wzy.util.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class HttpClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);


    @SneakyThrows
    public static JSONObject doGet(String url) {
        CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
        HttpGet post = new HttpGet();
        try {
            post.setURI(new URI(url));
            post.addHeader("Content-Type", "application/json;charset=UTF-8");
        } catch (URISyntaxException e) {
            throw new HttpException("请求url格式错误。" + e.getMessage());
        }
        /**
         * 设置超时时间
         */
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000)
                .setConnectTimeout(2000)
                .build();
        post.setConfig(requestConfig);

        JSONObject response = null;
        long start = System.currentTimeMillis();
        try {
            HttpResponse res = httpclient.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                response = JSON.parseObject(result);
            }
        } catch (Exception e) {
            System.out.println("链接失败");
            long end = System.currentTimeMillis();
            System.out.println("花费时间 " + (start - end) / 1000 + "秒");
            LOGGER.error("连接失败”" + url + "花费时间 " + (start - end) / 1000 + "秒");

        }
        if (response != null) {

            System.out.println(response);

        }
        return response;
    }


    @SneakyThrows
    public static JSONObject sendGet(String Api, String method, String AppKey, String appSecret, String accesstoken, String paramJson) {
        //API协议版本，当前版本为2
        String v = "2";
        //业务参数   page：第几页（第一页为0，最大为99）    size：每页返回条数，最多支持100条

        System.out.println();

        //时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        String str = appSecret + "app_key" + AppKey + "method" + method + "param_json" + paramJson + "timestamp" + date + "v" + v + appSecret;

        //创建URLBuilder
        URIBuilder uriBuilder = new URIBuilder(Api);
        //设置参数
        uriBuilder.setParameter("app_key", AppKey);
        uriBuilder.setParameter("method", method);
        uriBuilder.setParameter("access_token", accesstoken);
        uriBuilder.setParameter("param_json", paramJson);
        uriBuilder.setParameter("timestamp", date);
        uriBuilder.setParameter("v", "2");
        uriBuilder.setParameter("sign", JavaSign.stringToMD5(str));


        //1.创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //要求：设置请求的地址是：http://yun.itheima.com/search?keys=java
        String content = null;
        //2.创建HttpGet对象，设置URL地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        System.out.println("发送请求的信息：" + httpGet);
        //使用httpClient发起响应获取repsonse
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            //4.解析响应，获取数据
            //判断状态码是否是200
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                content = EntityUtils.toString(httpEntity, "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JSONObject jsonObject1 = JSONObject.parseObject(content);
        return jsonObject1;

    }





    public static void main(String[] args) {

//        System.err.println(sendGet1("", ""));

    }


}
